import React from 'react';
import AceEditor from 'react-ace';
import {Button, Input, message} from 'antd';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import actions from 'store/actions/app-configs';
import styles from './editor.scss';
class Editor extends React.Component {
  constructor(props) {
    super(props);
    const location = this.props.location || {};
    let {data = {}} = location;
    this.state = {
      appName: data.appName || '',
      configs: data.configs || '',
      isEdit: data.type === 'edit',
      id: data.id
    };
  }

  async submit() {
    const {id, isEdit, appName, configs} = this.state;
    const {dispatch} = this.props;
    let res;
    if (isEdit) {
      res = await dispatch(actions.editConfig(id, configs, appName));
    } else {
      res = await dispatch(actions.addConfig(appName, configs));
    }
    if (res.code === '0') {
      message.info('提交成功');
      this.props.history.goBack();
    } else {
      message.error(res.msg);
    }
  }

  onNameChange = (e) => {
    this.setState({
      appName: e.target.value
    });
  };

  onConfigsChange = (value) => {
    this.setState({
      configs: value
    });
  };

  render() {
    return (
      <div className={styles.wrap}>
        <div className={styles.head}>
          <Button
            type="primary"
            onClick={() => {
              this.submit();
            }}
          >
            提交
          </Button>
        </div>
        <div className={styles.inputWrap}>
          <Input type="text" placeholder="输入应用名" value={this.state.appName} onChange={this.onNameChange} />
        </div>
        <AceEditor
          mode="json"
          theme="xcode"
          name="configs"
          onChange={this.onConfigsChange}
          editorProps={{$blockScrolling: true}}
          width="100%"
          height="500px"
          showPrintMargin={false}
          ref="aceSource"
          value={this.state.configs}
        />
      </div>
    );
  }
}

function select(state) {
  return state;
}

export default withRouter(connect(select)(Editor));
